/*
 * version May 28, 2011 Thach created constructor and parse method
 * version May 28, 2011 Thach changed theFile type from FileInputStream to Readable. 
 * version May 31, 2011 Gavin changed myTimeSlot to myTimeSet
 * version June 01, 2011 Thach Changed theFile type from Readable to File
 */
package parsers;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Collections;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
import java.util.StringTokenizer;

import data.ClassDays;
import data.TimeSlot;

/**
 * @author Thach
 * @version June 01, 2011
 */
public class TimeSlotParser {
	private static final String SEPARATOR = ",";
	private final Set<TimeSlot> myTimeSet;

	/**
	 * Parses a file for a Set of TimeSlots.
	 * @pre theFile is formatted appropriately. Specifically 
	 * each line is of the form:
	 * int startTime,int endTime,ClassDay classDay1,...,
	 * @pre theFile != null
	 * @post creates a set of TimeSlot objects
	 * @param theFile
	 * @throws FileNotFoundException
	 * @throws NumberFormatException
	 */
	public TimeSlotParser(final File theFile) throws FileNotFoundException {
		myTimeSet = new HashSet<TimeSlot>();
		parse(theFile);
	}

	/**
	 * @param theFile
	 * @throws FileNotFoundException
	 */
	private void parse(final File theFile) throws FileNotFoundException {
		Scanner scan = new Scanner( theFile);
		while (scan.hasNextLine()) {
			StringTokenizer line = new StringTokenizer(scan.nextLine(), SEPARATOR);
			final int startTime = Integer.parseInt(line.nextToken()); //parseInt() Throws NumberFormatException
			final int endTime = Integer.parseInt(line.nextToken());
			final Set<ClassDays> days = new HashSet<ClassDays>();
			while (line.hasMoreTokens()) {
				days.add(ClassDays.valueOf(line.nextToken()));
			}
			myTimeSet.add(new TimeSlot(days, startTime, endTime));
		}
	}
	
	public Set<TimeSlot> getTimeSet() {
		return Collections.unmodifiableSet(myTimeSet);
	}

	/**
	 * for testing purposes only
	 */
	public String log() {
		String str = "";
		for (TimeSlot time : myTimeSet) {
			str += time.toString() + "\n";
		}
		return str;
	}

}
